import React, { Component } from 'react'
import Header from '../../components/Header/Header'
import { Button, SwipeAction, Dialog, Toast } from 'antd-mobile';
import { reqcartadd, reqcartdelete, reqcartedit, reqcartlist } from '../../http/api'
import { $pre } from '../../http/http';
import yImg from '../../assets/img/y.jpeg'
import nImg from '../../assets/img/n.jpeg'
import './Shop.less'
import { filterPrice } from '../../filters';
export default class Shop extends Component {
  constructor() {
    super()
    this.state = {
      arr: [],
      //全选
      allChecked: false
    };
    this.isRequest = true;
  }

  componentDidMount() {
    //发请求
    this.getList()

  }
  //请求列表
  async getList() {
    let res = await reqcartlist({
      uid: JSON.parse(sessionStorage.getItem('userInfo')).uid
    });
    if (res.data.code == 200) {
      let arr = res.data.list[1].content ? res.data.list[1].content : [];
      let oldArr = this.state.arr;
      // 补checked
      arr.forEach((item) => {
        let obj = oldArr.find(i => i.id === item.id)
        item.checked = obj?obj.checked: false
      })
      this.setState({
        arr: arr,
        allChecked: arr.length > 0 ? arr.every(item => item.checked) : false
      }, () => {
        this.isRequest = true;
      })
    }
  }

  //数量+
  async add(id) {
    let res = await reqcartedit({ id: id, type: 2 })
    if (res.data.code == 200) {
      Toast.show({
        content: res.data.msg
      })

      //请求列表
      this.getList();
    }
  }

  //数量-
  async sub(id, num) {

    if (num > 1) {
      if (this.isRequest) {
        //增加一个状态isrequest，有雨用户可能多次连点，为了防止连点多次发请求，所以设置一个状态，真就发请求，假就不能发请求，一旦要发请求，立刻将isrequest=false，知道新的列表回来了，才改为true，方便下一次请求
        this.isRequest = false;
        let res = await reqcartedit({ id: id, type: 1 })
        if (res.data.code == 200) {
          Toast.show({
            content: res.data.msg
          })
          //请求列表
          this.getList();
        }
      }
    } else {
      Toast.show({
        content: '宝贝不能再少了'
      })

    }
  }
  async del(id) {
    let res = await reqcartdelete({ id: id })
    if (res.data.code == 200) {
      Toast.show({
        content: res.data.msg
      })
      //请求列表
      this.getList();
    }
  }

  //全选
  changeAll() {
    this.setState({
      allChecked: !this.state.allChecked
    }, () => {
      this.state.arr.forEach(item => {
        item.checked = this.state.allChecked
      });
      //放回去
      this.setState({
        arr: this.state.arr
      })
    })

  }
  //修改一个
  changeOne(index) {
    let { arr } = this.state
    arr[index].checked = !arr[index].checked;

    //放
    this.setState({
      arr: arr,
      allChecked: arr.every(item => item.checked)
    })
  }


  render() {
    let { arr, allChecked } = this.state;

    //总价
    let allPrice = arr.reduce((v, i) => (i.checked ? v + i.price * i.num : v),0)
    return (
      <div className='shop'>
        <Header title='购物车'></Header>
        {arr.map((item, index) => (
          <SwipeAction
            key={item.id}
            closeOnAction={false}
            closeOnTouchOutside={false}
            rightActions={[
              {
                key: 'delete',
                text: '删除',
                color: 'danger',
                onClick: async () => {
                  await Dialog.confirm({
                    content: '确定要删除吗？',
                    onConfirm: () => {
                      this.del(item.id)
                    }
                  })
                },
              },
            ]}
          >
            <div className='item' >
              <img className='checkbox' src={item.checked ? yImg : nImg} alt="" />
              <img className='img' onClick={() => this.changeOne(index)} src={$pre + item.img} alt="" />
              <div className='right'>
                <h3>name:{item.goodsname}</h3>
                <div>price:{filterPrice(item.price)}</div>
                <div>
                  <Button onClick={() => this.sub(item.id, item.num)}>-</Button>
                  {item.num}
                  <Button onClick={() => this.add(item.id)}>+</Button>
                </div>
              </div>

            </div>
          </SwipeAction>
        )
        )}
        {/* 全选总价 */}
        <div className='footer'>
          <div className='allChecked' onClick={() => this.changeAll()}>
            <img className='checkbox' src={allChecked ? yImg : nImg} alt="" />全选
          </div>
          <div className='allPrice'>￥{filterPrice(allPrice)}</div>
        </div>
      </div>
    )
  }
}
